﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using CLEXA.DataContracts;

namespace CLEXA.Service.Helpers
{
    public class QueryBuilder : IQueryBuilder
    {
        private static string GenerateSQL(AggregateData aggregate)
        {
            switch (aggregate.AggregateType)
            {
                case AggregateTypeData.Average:
                    return "CAST(AVG(" + aggregate.Column + ") AS DOUBLE)";

                case AggregateTypeData.Count:
                    return "CAST(COUNT(*) AS DOUBLE)";

                case AggregateTypeData.Max:
                    return "CAST(MAX(" + aggregate.Column + ") AS DOUBLE)";

                case AggregateTypeData.Min:
                    return "CAST(MIN(" + aggregate.Column + ") AS DOUBLE)";

                case AggregateTypeData.Sum:
                    return "CAST(SUM(" + aggregate.Column + ") AS DOUBLE)";

                default:
                    throw new NotSupportedException(aggregate.AggregateType.ToString());
            }
        }

        public string GenerateSQL(QueryData queryData)
        {
            StringBuilder builder = new StringBuilder();

            builder.Append("SELECT TOP ");
            builder.Append(queryData.MaxResultCount);
            builder.Append(" ");

            builder.Append(GenerateSQL(queryData.Aggregates[0]));
            for (int i = 1; i < queryData.Aggregates.Count; i++)
            {
                builder.Append(", " + GenerateSQL(queryData.Aggregates[i]));
            }
            foreach (string group in queryData.GroupByColumns)
            {
                builder.Append(", CAST(" + group + " AS VARCHAR) AS " + group);
            }
            builder.AppendLine();

            builder.AppendLine("FROM " + queryData.TableName);

            builder.Append("GROUP BY ");
            builder.Append(queryData.GroupByColumns[0]);
            for (int i = 1; i < queryData.GroupByColumns.Count; i++)
            {
                builder.Append(", " + queryData.GroupByColumns[i]);
            }
            builder.AppendLine();

            return builder.ToString();
        }
    }
}